package com.sicpa.common.utils;

import javax.net.ssl.HttpsURLConnection;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;

/**
 * HTTP工具类
 */
public class HttpUtil {

	private static SslContextUtils sslContextUtils = new SslContextUtils();

	/**
	 * 发送post请求
	 * @param postUrl
	 * @param data
	 * @return
	 */
	public static String sendDataByPost(String postUrl, String data) {
		StringBuilder sb = new StringBuilder();
		try {
			URL url = new URL(postUrl);
			HttpURLConnection httpConn = (HttpURLConnection) url.openConnection();

			if (httpConn instanceof HttpsURLConnection) {
				sslContextUtils.initHttpsConnect((HttpsURLConnection) httpConn);
			}

			httpConn.setRequestMethod("POST");
			httpConn.setDoOutput(true);
			httpConn.setDoInput(true);
			httpConn.setRequestProperty("Content-type", "application/json");
			httpConn.setConnectTimeout(60000);
			httpConn.setReadTimeout(60000);
			// 发送请求
			httpConn.getOutputStream().write(data.getBytes("UTF-8"));
			httpConn.getOutputStream().flush();
			httpConn.getOutputStream().close();
			// 获取输入流
			BufferedReader reader = new BufferedReader(new InputStreamReader(httpConn.getInputStream(), "UTF-8"));
			char[] buf = new char[1024];
			int length = 0;
			while ((length = reader.read(buf)) > 0) {
				sb.append(buf, 0, length);
			}
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ProtocolException e) {
			e.printStackTrace();
		} catch (MalformedURLException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

}
